package com.lagou.filter;

import com.lagou.bean.CountTimeModel;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


@Activate(group = {CommonConstants.CONSUMER})
public class DubboInvokeFilter implements Filter {
    //日志
    private static Logger log = LoggerFactory.getLogger(DubboInvokeFilter.class);

    // 开始打印时间
    private long startPrintTime = 0L;


    List<CountTimeModel> modelList = new ArrayList();


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        //计算方法调用时间
        long start = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long elapsed = System.currentTimeMillis() - start;

        CountTimeModel countTimeModel = new CountTimeModel();
        countTimeModel.setElapsed(elapsed);

        //系统当前时间
        countTimeModel.setTime(System.currentTimeMillis());

        modelList.add(countTimeModel);

        //五秒输出一次
        if (System.currentTimeMillis() - startPrintTime >= 5 * 1000) {
            System.out.println("Method:" + invocation.getMethodName() + "========>TP90耗时:" + tpCount(modelList, 90) + "ms;======>TP99耗时:"
                    + tpCount(modelList, 99)+"ms");
            // 开始打印时间重新赋值
            startPrintTime = System.currentTimeMillis();
        }

        return result;
    }


    /**
     * 计算TP90，TP99等
     *
     * @param list
     * @param percent
     * @return
     */
    private static int tpCount(List<CountTimeModel> list, int percent) {
        List<Integer> timeList = new ArrayList();
        for (CountTimeModel c : list) {

            timeList.add((int) c.getElapsed());
        }
        return tp(timeList, percent);
    }

    private static int tp(List<Integer> times, int percent) {
        float percentF = (float) percent / 100;
        //获取到 90 99 索引
        int index = (int) (percentF * times.size() - 1);
        //从小到大排序
        Collections.sort(times);
        //获取到 90 99 索引 方法调用耗时
        return times.get(index);
    }
}
